package elec315.chatroom.client;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import elec315.chatroom.msg.authentication.ChatLoginReqMsg;
import elec315.chatroom.msg.authentication.ChatLogoutReqMsg;
import elec315.chatroom.msg.chat.ChatBroadcastReqMsg;
import elec315.chatroom.msg.user.ChatGetUserListReqMsg;
import elec315.chatroom.net.ClientSocketHandler;

public class ClientRequestHandler {

	private static final Log logger = LogFactory.getLog(ClientRequestHandler.class);

	private final ClientSocketHandler clientSocketHandler;

	public ClientRequestHandler(ClientSocketHandler clientSocketHandler) {
		super();
		this.clientSocketHandler = clientSocketHandler;
	}

	public void login(String userId) {
		if (StringUtils.isNotBlank(userId)) {
			ChatLoginReqMsg reqMsg = new ChatLoginReqMsg(userId, new Date(), userId);
			clientSocketHandler.writeMessage(reqMsg);
		} else {
			logger.error("Invalid userId: " + userId);
		}
	}

	public void logout(String userId) {
		if (StringUtils.isNotBlank(userId)) {
			ChatLogoutReqMsg reqMsg = new ChatLogoutReqMsg(userId, new Date(), userId);
			clientSocketHandler.writeMessage(reqMsg);
		} else {
			logger.error("Invalid userId: " + userId);
		}
	}

	public void broadcast(String message) {
		String userId = clientSocketHandler.getUserId();
		ChatBroadcastReqMsg reqMsg = new ChatBroadcastReqMsg(userId, new Date(), userId, message);
		clientSocketHandler.writeMessage(reqMsg);
	}
	
	public void getUserList() {
		String userId = clientSocketHandler.getUserId();
		ChatGetUserListReqMsg reqMsg = new ChatGetUserListReqMsg(userId, new Date());
		clientSocketHandler.writeMessage(reqMsg);
	}

}
